package upicgame.user.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import upicgame.user.dao.UserDao;
import upicgame.entity.User;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: upicgame
 * @description: 用户管理dao实现类
 * @author: lhq
 * @create: 2019-12-17 09:53
 */
@Repository
public class UserDaoImpl implements UserDao {
	@Resource
	private SessionFactory sessionFactory;

	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}

	@Override
	public boolean addUser(User user) {
		getSession().save(user);
		System.out.println("添加用户成功");
		return true;
	}

	@Override
	public boolean deleteUser(User user) {
		getSession().delete(user);
		System.out.println("删除用户成功");
		return true;
	}

	@Override
	public boolean updateUser(User user) {
		getSession().update(user);
		System.out.println(user);
		System.out.println("更改用户信息成功");
		return true;
	}

	@Override
	public User findUser(Integer id,String idType) {
		String hql = "select new User(id,uid,name,password,email,phone,address,userType,img,money) from User where "+idType+" = :ids";
		System.out.println(hql);
		User user = (User) this.getSession().createQuery(hql).setParameter("ids",id).uniqueResult();
		System.out.println(user);
		return user;
	}

	@Override
	public User findUser(String info,String infoType) {
		String hql = "select new User(id,uid,name,password,email,phone,address,userType,img,money) from User where "+infoType+" = :info";
		System.out.println(hql);
		User user = (User) this.getSession().createQuery(hql).setParameter("info",info).uniqueResult();
		System.out.println(user);
		return user;
	}


	@Override
	public List<User> findAllPage(Integer currentPage,Integer size) {
		String hql = "select new User(id,uid,name,password,email,phone,address,userType,img,money) from User";
		Query query = this.getSession().createQuery(hql);
		query.setFirstResult((currentPage-1)*size);
		query.setMaxResults(size);
		return (List<User>) query.list();
	}

	@Override
	public Long totalCount(String name) {
		Query query = this.getSession().createQuery("select count(*) from "+ name);
		return (Long)query.uniqueResult();
	}
}
